# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 2020-08-31 23:05:12
# @Last Modified by: CPS
# @Last Modified time: 2020-09-22 14:43:00
# @file_path Z:\CPS\IDE\sublime text\3176x32前端\Data\Packages\testt\fileheader\testtFileheader.py
# @Filename testtFileheader.py
#
#
import sublime
import sublime_plugin
import os
import datetime

TMPL_HEADER_PATH = ''

#每次插件加载完都会触发这个函数
def plugin_loaded():
    #print('testt: 加载成功.\n当前系统版本{ver}, 当前系统:{os}'.format(ver=sublime.version(),os=sublime.platform()))
    global TMPL_HEADER_PATH
    TMPL_HEADER_PATH = os.path.join(sublime.packages_path(),"testt","fileheader","header")
    print(TMPL_HEADER_PATH)


class TesttAddFileHeader(sublime_plugin.TextCommand):
    def run(self,edit):
        tmplfile = ''
        #获取配置
        settings = self.get_settings()
        if not settings:
            return

        # 获取对应的tmpl关系
        template = settings['template']
        info = settings['headerInfo']

        # 文件字符串少于2的话,当作是一个新文件,添加创建时间
        if self.view.size() <= 1:
            info = self.on_add_file(info)
        info = self.on_modi_file(info)
        res = ''

        # 判断当前格式是否有对应的模版文件
        tmplfile = self.get_tmpl(template)

        # 验证 tmpl文件
        if not os.path.exists(tmplfile):
            return print('没有发现tmpl文件'+tmplfile)

        # 读取tmpl文件
        res = ''
        with open(tmplfile,'r',encoding='utf8') as tmpl:
            for each in tmpl.readlines():
                for key,val in info.items():
                    each = each.replace('{{'+key+'}}',val)
                res+=each

        # 插入文件头
        if res:
            self.view.insert(edit,0,res)

    def get_tmpl(self,template):
        (name,ext) = os.path.splitext(self.view.file_name())
        ext = ext.replace('.','')
        if ext in template.keys():
            return os.path.join(TMPL_HEADER_PATH,template[ext])+'.tmpl'

    def get_settings(self):
        settings = self.view.settings().get('testt')
        if settings is None:
            settings = sublime.load_settings('testt.sublime-settings')

        if settings.has('stylus_beauty_options'):
            tmp = settings.get('file_header_options')
            return tmp

    def on_add_file(self,info):
        info['create_time'] = self.get_now(info['create_time'])
        return info

    def on_modi_file(self,info):
        # datetime.datetime.now()
        info['last_modified_time'] = self.get_now(info['last_modified_time'])
        info['file_path'] = os.path.dirname(self.view.file_name())
        info['file_name'] = os.path.basename(self.view.file_name())
        return info

    def get_now(self,fmat):
        try:
            if not fmat:
                fmat = r'%Y-%m-%d %H:%M:%S'
            return datetime.datetime.now().__format__(fmat)
        except Exception as e:
            return datetime.datetime.now().__format__(r'%Y-%m-%d %H:%M:%S')